package com.budwk.app.sqfw.services.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.constants.DictConstants;
import com.budwk.app.sqfw.dto.SimpleCenSusPaperQueryDTO;
import com.budwk.app.sqfw.models.Sqfw_cenSusPaper;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.services.SqfwCenSusPaperService;
import com.budwk.app.sqfw.vo.AreaAddressVo;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysDictService;
import com.budwk.app.sys.services.SysLogService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.sys.vo.SysDictVO;
import com.budwk.app.util.AuthorityUtil;
import com.budwk.app.util.StrUtil;
import com.budwk.starter.database.service.BaseServiceImpl;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.trans.Trans;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ZY.Wang
 * @since 2023/10/23
 */
@IocBean(args = {"refer:dao"})
@Slf4j
public class SqfwCenSusPaperServiceImpl extends BaseServiceImpl<Sqfw_cenSusPaper> implements SqfwCenSusPaperService {
    public SqfwCenSusPaperServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private SysUserService sysUserService;
    @Inject
    private SysLogService sysLogService;
    @Inject
    private SysDictService sysDictService;

    @Override
    public void add(Sqfw_cenSusPaper cenSusPaper) {
        String cardId = cenSusPaper.getCardId();
        // 添加之前要判断一下身份证号码是否重复
        Cnd userExistCnd = Cnd.NEW();
        userExistCnd.and("unit_id", "=", cenSusPaper.getUnitId());
        userExistCnd.and("courtyard", "=", cenSusPaper.getCourtyard());
        userExistCnd.and("house_number", "=", cenSusPaper.getHouseNumber());
        if (StringUtils.isNotBlank(cardId)) {
            userExistCnd.and("card_id", "=", cardId);
        }
        userExistCnd.and("name", "=", cenSusPaper.getName());
        Sqfw_cenSusPaper queryPaper = fetch(userExistCnd);
        if (queryPaper != null) {
            if (StringUtils.isBlank(queryPaper.getLatestStatus())) {
                BeanUtil.copyProperties(queryPaper, cenSusPaper);
                return;
            } else if (queryPaper.getLatestStatus().equals("搬离")) {
                // 如果这个人已经是搬离的状态，那么这个时候又添加进来，说明是又搬进来了
                queryPaper.setLatestStatus("");
                queryPaper.setStatusUpdateDate(null);
                queryPaper.setUpdateDate(new Date());
                update(queryPaper);
                return;
            }
        }
        if (StringUtils.isNotBlank(cardId)) {
            try {
                int age = IdcardUtil.getAgeByIdCard(cardId);
                DateTime birthDate = IdcardUtil.getBirthDate(cardId);

                String genderStr = "男";
                int gender = IdcardUtil.getGenderByIdCard(cardId);  // 0是女 1是男
                genderStr = gender == 0 ? "女" : genderStr;

                cenSusPaper.setAge(age);
                cenSusPaper.setBirthday(birthDate);
                cenSusPaper.setGender(genderStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        cenSusPaper.setCreateDate(new Date());
        insert(cenSusPaper);
    }

    @Override
    public int updateCenSusPaper(Sqfw_cenSusPaper cenSusPaper) {
        // 更新之前首先判断一下数据库里有没有这个数据
        Sqfw_cenSusPaper existPeople = fetch(cenSusPaper.getId());
        if (existPeople == null) {
            return 0;
        }
        String cardId = cenSusPaper.getCardId();
        if (StringUtils.isNotBlank(cardId)) {

            try {
                int age = IdcardUtil.getAgeByIdCard(cardId);
                DateTime birthDate = IdcardUtil.getBirthDate(cardId);

                String genderStr = "男";
                int gender = IdcardUtil.getGenderByIdCard(cardId);  // 0是女 1是男
                genderStr = gender == 0 ? "女" : genderStr;

                cenSusPaper.setAge(age);
                cenSusPaper.setBirthday(birthDate);
                cenSusPaper.setGender(genderStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String latestStatus = cenSusPaper.getLatestStatus();
        if (StringUtils.isNotBlank(latestStatus)) {
            if (latestStatus.contains("搬离") || latestStatus.contains("死亡")) {
                cenSusPaper.setStatusUpdateDate(new Date());
            }
        }

        cenSusPaper.setUpdateDate(new Date());
        updateIgnoreNull(cenSusPaper);

        return 1;
    }

    private void checkSqfwCenSusPaper(List<Sqfw_cenSusPaper> papers) {
        if (papers == null || papers.size() == 0) {
            return;
        }
        // 检查是否存在重名的姓名和身份证号
        List<String> cList1 = papers.stream().map(Sqfw_cenSusPaper::getCardId).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        List<String> cList2 = cList1.stream().distinct().collect(Collectors.toList());
        if (cList1.size() != cList2.size()) {
            throw new AppException("身份证号重复");
        }
        List<String> nList1 = papers.stream().map(Sqfw_cenSusPaper::getName).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        List<String> nList2 = nList1.stream().distinct().collect(Collectors.toList());
        if (nList1.size() != nList2.size()) {
            throw new AppException("名字重复");
        }
        // 校验身份证
//        for (String idCard : cList2) {
//            if (!IdcardUtil.isValidCard(idCard)) {
//                throw new AppException("身份证号["+ idCard +"]不正确，请重新输入！");
//            }
//        }
    }

    private void buildCenSusPaper(List<Sqfw_cenSusPaper> papers, Sqfw_formSummary formSummary) {
        List<SysDictVO> sysDicts = sysDictService.listDictByCode(DictConstants.SPECIAL_PERSONNEL_TYPES);
        List<String> ids = Lists.newArrayList();
        Sys_user user = sysUserService.getUserById(SecurityUtil.getUserId());
        for (Sqfw_cenSusPaper paper : papers) {
            //zhangp 2024-01-09 检擦该用户是否存在用户名+详细地址确定唯一
            if (StringUtils.isBlank(paper.getId())) {
                Cnd cnd = Cnd.NEW();
                cnd.and("name", "=", paper.getName());
                cnd.and("detail_address", "=", StrUtil.getHouseAddress(formSummary));
                List<Sqfw_cenSusPaper> cenSusPapers = query(cnd);
                ids = cenSusPapers.stream().map(Sqfw_cenSusPaper::getId).collect(Collectors.toList());
            }
            paper.setProvince(formSummary.getProvince())
                    .setCity(formSummary.getCity())
                    .setDistrict(formSummary.getDistrict())
                    .setCounty(formSummary.getCounty())
                    .setCommunity(formSummary.getCommunity())
                    .setUnitId(formSummary.getUnitId())
                    .setUnitName(formSummary.getUnitName())
                    .setGrid(formSummary.getA3())
                    .setCourtyard(formSummary.getA1())
                    .setSqfwId(formSummary.getSqfwId())
                    .setWorkOrderId(formSummary.getWorkOrderId())
                    .setSqfwFlowId(formSummary.getSqfwFlowId())
                    .setUpdateBy(SecurityUtil.getUserId())
                    //.setUpdateDate(new Date())
                    //2024-01-10 产品要求时间为formSummary的fillDate
                    .setUpdateDate(formSummary.getFillDate())
                    .setBuilding(formSummary.getA4())
                    .setSurvey(formSummary.getA20())
                    .setHouseNumber(formSummary.getA5())
                    //.setDetailAddress(StrUtil.getHouseAddress(formSummary))
                    .setDetailAddress("自建房".equals(formSummary.getA18()) ? formSummary.getA15() : StrUtil.getHouseAddress(formSummary))
                    //zhangp 2024-01-09 将“巡查情况”存入patrolSum，“发现问题”存入identifyIssue,数据归属存入：attribution
                    .setPatrolSum(formSummary.getA19())
                    .setIdentifyIssue(formSummary.getA23())
                    .setPersonIds(ids)
                    //更新对应提交人信息
                    .setUpadteUserName(user.getUsername())
                    .setUpadteUserPhone(user.getMobile());

            if (StringUtils.isNotEmpty(paper.getCardId()) && IdcardUtil.isValidCard(paper.getCardId())) {
                paper.setAge(IdcardUtil.getAgeByIdCard(paper.getCardId()))
                        .setBirthday(IdcardUtil.getBirthDate(paper.getCardId()))
                        .setGender(IdcardUtil.getGenderByIdCard(paper.getCardId()) == 0 ? "女" : "男");
            }
            // 特殊人员类型
            paper.setSpecialMarkIds(CommonComponent.getSpecialMarkIds(paper.getSpecialMark(), sysDicts));
        }
    }

    @Override
    public List<Sqfw_cenSusPaper> addOrUpdateByFormSummaryStr(String str, Sqfw_formSummary formSummary) {
        List<Sqfw_cenSusPaper> papers = JSONObject.parseObject(str, new TypeReference<>() {
        });
        // 1 前置参数校验
        checkSqfwCenSusPaper(papers);
        // 2 构建参数
        buildCenSusPaper(papers, formSummary);
        // 3 参数入库
        List<Sqfw_cenSusPaper> finalPapers = papers;
        Trans.exec(() -> {
            for (Sqfw_cenSusPaper paper : finalPapers) {
                paper.setSqfwId(formSummary.getSqfwId());
                if (StringUtils.isBlank(paper.getId())) {
                    //zhangp 2024-01-09 app新增入户调查人员信息时验证是否存在用户存在则更新
                    if (!paper.getPersonIds().isEmpty()) {
                        for (String id : paper.getPersonIds()) {
                            paper.setId(id);
                            updateData(paper);
                        }
                    } else {
                        //zhangp 2024-01-10 取到当前登录用户五级
                        Sys_user user = sysUserService.getUserById(SecurityUtil.getUserId());
                        String attribution = user.getProvince() + user.getCity() + user.getDistrict() + user.getCounty() + user.getCommunity();
                        paper.setAttribution(attribution);
                        insertData(paper);
                    }
                    continue;
                }
                updateData(paper);
            }
        });
        return finalPapers;
    }

    private void insertData(Sqfw_cenSusPaper paper) {
        Sys_user user = sysUserService.fetch(SecurityUtil.getUserId());
        if (StringUtils.isNotEmpty(paper.getCardId())) {
            Sqfw_cenSusPaper sqfwCenSusPaper = fetch(Cnd.where(Sqfw_cenSusPaper::getCardId, "=", paper.getCardId()));
            if (sqfwCenSusPaper != null) {
                paper.setId(sqfwCenSusPaper.getId());
                BeanUtil.copyProperties(paper, sqfwCenSusPaper);
                if (StringUtils.isEmpty(paper.getLatestStatus())) {
                    sqfwCenSusPaper.setLatestStatus("").setStatusUpdateDate(new Date());
                }
                sqfwCenSusPaper.setUpdateBy(user.getId()).setUpdateDate(new Date());
                update(sqfwCenSusPaper);
                return;
            }
        }
        paper.setCreateBy(user.getId())
                .setCreateDate(new Date())
                .setCreateUserName(user.getUsername())
                .setCreateUserPhone(user.getMobile());
        insert(paper);
    }

    private void updateData(Sqfw_cenSusPaper paper) {
        Sqfw_cenSusPaper susPaper = fetch(paper.getId());
        //zhangp 2024-01-10 取到当前登录用户五级
        Sys_user user = sysUserService.getUserById(SecurityUtil.getUserId());
        String attribution = user.getProvince() + user.getCity() + user.getDistrict() + user.getCounty() + user.getCommunity();

        if (susPaper == null) {
            paper.setAttribution(attribution);
            // 特殊情况，历史数据做新增
            insertData(paper);
            return;
        }
        //paper.setSqfwId(StringUtils.isBlank(susPaper.getSqfwId()) ? paper.getSqfwId() : susPaper.getSqfwId().contains(paper.getSqfwId()) ? susPaper.getSqfwId() : susPaper.getSqfwId() + "," + paper.getSqfwId());
        paper.setAttribution(StringUtils.isBlank(susPaper.getAttribution()) ? attribution : susPaper.getAttribution().contains(attribution) ? susPaper.getAttribution() : susPaper.getAttribution() + "," + attribution);
        paper.setId(susPaper.getId());
        if (StringUtils.isNotEmpty(paper.getCardId())) {
            // 1 删除其他数据
            Sqfw_cenSusPaper sqfwCenSusPaper = fetch(Cnd.where(Sqfw_cenSusPaper::getCardId, "=", paper.getCardId()));
            if (sqfwCenSusPaper != null) {
                if (!paper.getId().equals(sqfwCenSusPaper.getId())) {
                    this.delete(sqfwCenSusPaper.getId());
                    // 记录删除日志
                    sysLogService.insertDelLog(SecurityUtil.getUserId(), JSONObject.toJSONString(sqfwCenSusPaper),
                            Sqfw_cenSusPaper.class.getAnnotation(Table.class).value(),
                            "com.budwk.app.sqfw.services.SqfwCenSusPaperService.addOrUpdateByFormSummaryStr",
                            "/platform/sqfw/formSummary/generateHouseSurveyFormPdf");
                }
            }
            // 2 修改当前数据
            BeanUtil.copyProperties(paper, susPaper);
            susPaper.setUpdateDate(new Date()).setUpdateBy(SecurityUtil.getUserId());
            updateIgnoreNull(susPaper);
            return;
        }
        String latestStatus = paper.getLatestStatus();
        if (StringUtils.isNotBlank(latestStatus)) {
            if (latestStatus.contains("搬离") || latestStatus.contains("死亡")) {
                paper.setStatusUpdateDate(new Date());
            }
        }
        paper.setUpdateDate(new Date()).setUpdateBy(SecurityUtil.getUserId());
        updateIgnoreNull(paper);
    }

    @Override
    public List<Sqfw_cenSusPaper> listCenSusPaper(Sqfw_cenSusPaper cenSusPaper) {
        Cnd cnd = Cnd.NEW();
        if (StringUtils.isNotBlank(cenSusPaper.getProvince())) {
            cnd.and("province", "=", cenSusPaper.getProvince());
        }
        if (StringUtils.isNotBlank(cenSusPaper.getCity())) {
            cnd.and("city", "=", cenSusPaper.getCity());
        }
        if (StringUtils.isNotBlank(cenSusPaper.getDistrict())) {
            cnd.and("district", "=", cenSusPaper.getDistrict());
        }
        if (StringUtils.isNotBlank(cenSusPaper.getCounty())) {
            cnd.and("county", "=", cenSusPaper.getCounty());
        }
        if (StringUtils.isNotBlank(cenSusPaper.getCommunity())) {
            cnd.and("community", "=", cenSusPaper.getCommunity());
        }
        if (StringUtils.isNotBlank(cenSusPaper.getGrid())) {
            cnd.and("grid", "=", cenSusPaper.getGrid());
        }
        if (StringUtils.isNotBlank(cenSusPaper.getUnitId())) {
            cnd.and("unitId", "=", cenSusPaper.getUnitId());
        }

        cnd.orderBy("name", "asc");
        List<Sqfw_cenSusPaper> list = query(cnd);

        List<Sqfw_cenSusPaper> resultList = Lists.newArrayList();
        for (Sqfw_cenSusPaper susPaper : list) {
            if (StringUtils.isBlank(susPaper.getLatestStatus())) resultList.add(susPaper);
        }
        return resultList;
    }

    @Override
    public List<Sqfw_cenSusPaper> listHouseSurveyCenPeople(SimpleCenSusPaperQueryDTO queryDTO, String userId) {
        List<Sqfw_cenSusPaper> resultList = Lists.newArrayList();
        Sys_user loginUser = sysUserService.fetch(userId);
        log.info("listHouseSurveyCenPeople currentuser: {}", JSONObject.toJSONString(loginUser));
        if (loginUser == null) return resultList;
        Criteria cnd = Cnd.cri();
        SqlExpressionGroup criSql = cnd.where();
        Sqfw_cenSusPaper bean = new Sqfw_cenSusPaper();
        // 五级查询
        AreaAddressVo areaAddressVo = AuthorityUtil.checkCenSusPaperAreaPermission(bean);
        AuthorityUtil.commonPermissionEqualQuery(criSql, areaAddressVo);
        // 特殊人员查询
        List<String> specialMarkList = queryDTO.getSpecialMarkList();
        if (specialMarkList != null && specialMarkList.size() > 0) {
            if (specialMarkList.size() == 1) {
                criSql.andLike(Sqfw_cenSusPaper::getSpecialMarkIds, specialMarkList.get(0));
            } else {
                SqlExpressionGroup sqlExpressionGroup = Cnd.exps(Sqfw_cenSusPaper::getSpecialMarkIds, "like", "%" + specialMarkList.get(0) + "%");
                for (int i = 1; i < specialMarkList.size(); i++) {
                    SqlExpressionGroup sqlExpressionGroup1 = Cnd.exps(Sqfw_cenSusPaper::getSpecialMarkIds, "like", "%" + specialMarkList.get(i) + "%");
                    sqlExpressionGroup = sqlExpressionGroup.or(sqlExpressionGroup1);
                }
                criSql.and(sqlExpressionGroup);
            }
        }
        // 网格
        if (StringUtils.isNotEmpty(queryDTO.getGrid())) {
            criSql.andEquals(Sqfw_cenSusPaper::getGrid, queryDTO.getGrid());
        }
        log.info("listHouseSurveyCenPeople query condition: {}", cnd);
        return query(cnd);
    }
}
